const { pool } = require('../config/database');
const { formatDateTime } = require('../utils/dateFormatter');
const { logger } = require('../utils/logger');

class UserModel {
  // 创建用户
  async create(userData) {
    try {
      const [result] = await pool.execute(
        'INSERT INTO users (username, email, password, role) VALUES (?, ?, ?, ?)',
        [userData.username, userData.email, userData.password, userData.role || 'user']
      );
      return result.insertId;
    } catch (error) {
      // 处理特定的数据库错误
      if (error.code === 'ER_DUP_ENTRY') {
        if (error.message.includes('username')) {
          throw new Error('用户名已存在');
        }
        if (error.message.includes('email')) {
          throw new Error('邮箱已存在');
        }
        throw new Error('数据重复');
      }
      
      // 记录详细错误信息
      logger.error('创建用户数据库操作失败:', {
        error: error.message,
        code: error.code,
        stack: error.stack,
        userData: { ...userData, password: '***' } // 隐藏密码
      });
      
      throw new Error('创建用户失败: ' + error.message);
    }
  }

  // 通过ID获取用户
  async findById(id) {
    try {
      const [rows] = await pool.execute(
        'SELECT id, username, email, role, created_at, updated_at FROM users WHERE id = ? AND is_deleted = 0',
        [id]
      );
      return rows[0] ? this.formatUserData(rows[0]) : null;
    } catch (error) {
      logger.error('查询用户失败:', error);
      throw error;
    }
  }

  // 获取所有用户
  async findAll() {
    try {
      const [rows] = await pool.execute(
        'SELECT id, username, email, role, created_at, updated_at FROM users WHERE is_deleted = 0'
      );
      return rows.map(user => this.formatUserData(user));
    } catch (error) {
      logger.error('获取用户列表失败:', error);
      throw error;
    }
  }

  // 更新用户
  async update(id, userData) {
    const fields = [];
    const values = [];
    
    if (userData.username) {
      fields.push('username = ?');
      values.push(userData.username);
    }
    if (userData.email) {
      fields.push('email = ?');
      values.push(userData.email);
    }
    if (userData.password) {
      fields.push('password = ?');
      values.push(userData.password);
    }
    if (userData.role) {
      fields.push('role = ?');
      values.push(userData.role);
    }
    
    values.push(id);
    
    const [result] = await pool.execute(
      `UPDATE users SET ${fields.join(', ')} WHERE id = ?`,
      values
    );
    return result.affectedRows > 0;
  }

  // 删除用户
  async delete(id) {
    const [result] = await pool.execute(
      'DELETE FROM users WHERE id = ?',
      [id]
    );
    return result.affectedRows > 0;
  }

  // 通过用户名查找用户
  async findByUsername(username) {
    const [rows] = await pool.execute(
      'SELECT * FROM users WHERE username = ?',
      [username]
    );
    return rows[0];
  }

  // 通过邮箱查找用户
  async findByEmail(email) {
    const [rows] = await pool.execute(
      'SELECT * FROM users WHERE email = ?',
      [email]
    );
    return rows[0];
  }

  // 格式化用户数据
  formatUserData(user) {
    if (!user) return null;
    
    return {
      ...user,
      created_at: formatDateTime(user.created_at),
      updated_at: formatDateTime(user.updated_at),
    };
  }

  /**
   * 软删除用户
   * @param {number} id 用户ID
   * @returns {Promise<boolean>} 删除是否成功
   */
  async softDelete(id) {
    try {
      // 先检查用户是否存在且未删除
      const [user] = await pool.execute(
        'SELECT id FROM users WHERE id = ? AND is_deleted = 0',
        [id]
      );
      
      if (!user || user.length === 0) {
        throw new Error('用户不存在或已删除');
      }

      const [result] = await pool.execute(
        'UPDATE users SET is_deleted = 1, deleted_at = CURRENT_TIMESTAMP WHERE id = ? AND is_deleted = 0',
        [id]
      );
      return result.affectedRows > 0;
    } catch (error) {
      // 记录详细错误信息
      logger.error('软删除用户失败:', {
        error: error.message,
        code: error.code,
        stack: error.stack,
        userId: id
      });
      
      throw error;
    }
  }

  /**
   * 恢复已删除的用户
   * @param {number} id 用户ID
   * @returns {Promise<boolean>} 恢复是否成功
   */
  async restore(id) {
    try {
      const [result] = await pool.execute(
        'UPDATE users SET is_deleted = 0, deleted_at = NULL WHERE id = ? AND is_deleted = 1',
        [id]
      );
      return result.affectedRows > 0;
    } catch (error) {
      logger.error('恢复用户失败:', error);
      throw error;
    }
  }
}

module.exports = new UserModel(); 